package second.thread.threecore;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;

/**
 * @Author: heweiwei
 * @Date: 2/8/25 PM3:58
 * @Description:
 */
public class DatabaseConnectionExample {

     Semaphore semaphore = new Semaphore(2);

     CyclicBarrier cyclicBarrier = new CyclicBarrier(2);


    public static void main(String[] args) {

        DatabaseConnectionExample databaseConnectionExample = new DatabaseConnectionExample();

        // 创建 5 个线程来获取数据库连接
        for (int i = 0; i < 5; i++) {
            new Thread(databaseConnectionExample::getConnection).start();
        }
    }

    public void getConnection() {
        try {
            semaphore.acquire();
            System.out.println("Thread " + Thread.currentThread().getName() + " acquired a connection");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            semaphore.release();
            System.out.println(Thread.currentThread().getName() + " released a connection.");

        }
    }
}
